import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios"
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: [], //全部商品
    cartListtems: JSON.parse(localStorage.getItem('cartListtems')) || [],
    checkboxList: JSON.parse(localStorage.getItem('check')) || false,
    Allprices: 0
  },
  mutations: {
    // 拿到全部数据
    CARTLISTITEMS(state, item) {
      state.cartList = item
    },
    PUSHCARTITEM(state, item) {
      var isSHow = false;
      state.cartListtems.forEach((ele) => {
        if (ele._id === item._id) {
          ele.count++;
          isSHow = true
        }
        // console.log(state.cartList);
      })
      if (!isSHow) {
        item.count = 1;
        item.checked = false;
        state.cartListtems.push(item)
      }
      localStorage.setItem('cartListtems', JSON.stringify(state.cartListtems))
    },
    // 删除购物车商品
    DELEITEM(state, index) {
      state.cartListtems.splice(index, 1)
      localStorage.setItem('cartListtems', JSON.stringify(state.cartListtems))
    },
    // 点击复选框
    CHECKBOX(state, item) {
      item.checked = !item.checked
      console.log(item.checked);
      state.cartListtems.forEach((ele) => {
        if (ele._id === item._id) {
          ele.checked = item.checked
        }
      })
      let check = state.cartListtems.every(ele => {
        return ele.checked == true
      })
      state.checkboxList = check

      // 计算
      state.Allprices = 0;
      state.cartListtems.map((ele) => {
        if (ele.checked == true) {
          state.Allprices += ele.count * ele.salePrice
        }
      })
    },
    // 全选
    CHECKALL(state, e) {
      state.checkboxList = e; //赋值
      state.cartListtems.forEach(ele => {
        ele.checked = e;
      })
      state.Allprices = 0;
      state.cartListtems.map((ele) => {
        if (ele.checked == true) {
          state.Allprices += ele.count * ele.salePrice
        }
      })
    }
  },
  actions: {
    // 请求
    CARTLISTITEMS(context) {
      axios
        .get("./data.json")
        .then(res => {
          console.log(res.data.result.list);
          // this.cartList = res.data.result.list;
          context.commit('CARTLISTITEMS', res.data.result.list)
        })
        .catch(err => {
          console.log(err);
        });
    },
    //点击加入购物车
    PUSHCARTITEM(context, item) {
      context.commit('PUSHCARTITEM', item)
    },
    // 删除购物车商品
    DELEITEM(context, item) {
      context.commit('DELEITEM', item)
    },
    // 点击复选框
    CHECKBOX(context, item) {
      context.commit('CHECKBOX', item)
    },
    // 点击全选
    CHECKALL(context, e) {
      context.commit('CHECKALL', e)
    }
  },
  modules: {
  }
})
